const query=require('../db/mysql');
const {}=require('');
class ListController{
   //获取列表

   getList=async (ctx) => {
        // 分页  模糊查询  排序（sortBy 根据哪个字段 sortType 正序还是倒叙）  条件查询
        const {pageIndex,pageSize,keyword,sortBy,sortType, id} = ctx.query;
        // where order limit
        let sql = `select * from blogs where 1=1 `
        let sqlCount = `select count(id) as total from blogs where 1=1 `
        if(id) {
            sql += `and id = ${id} `
        }
        if(keyword) {
            // 21 条  模糊查找出来10条
            // 但是总数还是 21
            // 假设前端 每页5条那么前端 几页 5页
            // 当前点击第5页
            sql += `and title like "%${keyword}%" `
            sqlCount += `and title like "%${keyword}%" `
        }
        if(sortBy && sortType) {
            sql += `order by ${sortBy} ${sortType} `
        }
        if(pageIndex &&pageSize) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize}`
        }
        const list = await query(sql)
        const count = await query(sqlCount)
        ctx.body = {
            code:1,
            data: {
                list,
                total: count[0].total
            }
        }
    }
    // 添加博客
    addList = async (ctx)=>{
        const {title,content,author}=ctx.request.body;
        const sql = `insert into blogs(title,content,author,create_time) values("${title}","${content}","${author}",${Date.now()})`
        const data=await query(sql);
        if(data.affectedRows===1){
            ctx.body={
                code:1,
                data:{
                    id:data.insertId
                },
                message:"添加成功"
            }
        }else{
            ctx.body={
                code:-1,
                message:'添加失败'
            }
        }
    }
    //编辑博客
    editList = async (ctx)=>{
        const {id,title,content}=ctx.request.body;
        if(!title || !content){
            ctx.body={
                code:-1,
                message:'参数缺失'
            };
            return;
        }
        let sql=`update blogs set title="${title}",content="${content}" `;
        sql+=`where id="${id}"`;
        const data=await query(sql);
        if(data.affectedRows === 1) {
            ctx.body = {
                code:1,
                message:'编辑成功'
            }
        } else {
            ctx.body = {
                code:-1,
                message:'编辑失败'
            }
        }
    }
    //删除博客
    delList =async(ctx)=>{
        const {id}=ctx.params;
        const sql=`delete from blogs where id=${id}`;
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body={
                code:1,
                message:'删除成功'
            }
        }else{
            ctx.body={
                code:-1,
                message:"删除失败"
            }
        }
    }
}
module.exports = new ListController()
